package edu.zjucst.spb.controller.file;

import edu.zjucst.spb.conf.FileConfig;
import edu.zjucst.spb.domain.ResponseResult;
import edu.zjucst.spb.domain.entity.TbFile;
import edu.zjucst.spb.enums.OptStatusEnum;
import edu.zjucst.spb.enums.PrivilegeEnum;
import edu.zjucst.spb.service.FileService;
import edu.zjucst.spb.util.FileUtil;
import edu.zjucst.spb.util.SessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/files")
@Api(value = "文件管理", tags = {"文件管理"})
public class FileController {
    @Autowired
    FileService fileService;
    @Autowired
    FileConfig fileConfig;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public ResponseResult<Object> upload(
        // content-type: multipart/form-data
        @RequestPart("file") MultipartFile file,
        @RequestParam(value = "privilege", defaultValue = "0") Integer privilege) {
        // 校验参数
        if (PrivilegeEnum.getEnumByCode(privilege) == PrivilegeEnum.UNKNOWN) {
            return ResponseResult.error(OptStatusEnum.PARAM_ERROR);
        }
        log.info("upload {} file named {}", PrivilegeEnum.getEnumByCode(privilege).getName(), file.getOriginalFilename());
        //todo 校验登录状态

        return fileService.upload(file, privilege);
    }

    /**
     * 通过文件存储的id找到对应的存放路径后进行下载
     *
     * @return 下载文件
     */
    @GetMapping("/download/{id}")
    @ApiOperation("根据id进行文件下载")
    public ResponseEntity<byte[]> download(@PathVariable("id") Integer fileId) throws IOException {
        //todo 校验是否有下载权限

        TbFile file = fileService.getFileById(fileId);
        log.info("userid {} download fileid={}", SessionUtil.getUserId(), file.getId());
        return FileUtil.getResponseEntity(file.getName(), file.getPath());

    }

    /**
     * 通过id查询文件存储信息
     *
     * @return 文件的存储信息
     */
    @GetMapping("/detail/{id}")
    @ApiOperation("获得文件存储信息")
    public ResponseResult<Object> detail(@PathVariable("id") Integer fileId) throws IOException {
        TbFile file = fileService.getFileById(fileId);
        return ResponseResult.success(file);

    }

    @GetMapping("/public_file_ids")
    @ApiOperation("获得所有的公开文件的id")
    public ResponseResult<List<Integer>> publicFiles() {
        List<TbFile> tbFiles = fileService.listPublicFiles();
        List<Integer> ids = tbFiles.stream()
            .map(TbFile::getId)
            .collect(Collectors.toList());
        return ResponseResult.success(ids);
    }

}
